package com.handong.handserialprogram.ui;

import android.content.DialogInterface;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.handong.handserialprogram.R;
import com.handong.handserialprogram.constants.HttpConstant;
import com.handong.handserialprogram.utils.AppUtil;
import com.handong.handserialprogram.utils.AsyncHttpUtil;
import com.handong.handserialprogram.utils.JLog;
import com.handong.handserialprogram.utils.MD5Util;
import com.handong.handserialprogram.utils.NetWorkUtil;
import com.handong.handserialprogram.utils.SPUtil;
import com.handong.handserialprogram.utils.SystemUtil;
import com.handong.handserialprogram.widget.RectangleInputLayout;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by userKey on 2017/7/5.
 */

public class LoginBottomDialog extends BottomDialog {

    private static final String TAG = LoginBottomDialog.class.getSimpleName();
    private RectangleInputLayout mInputName, mInputPassword;
    private Button mLoginBtn;
    private TextView mDialogCancel, mLoginWarningTip;
    private LinearLayout mLoginLoadingLayout;

    private LoginCallback mCallback;
    private boolean mIsLogining = false;

    public static LoginBottomDialog create(FragmentManager fragmentManager, LoginCallback callback) {
        LoginBottomDialog dialog = new LoginBottomDialog();
        dialog.mCallback = callback;
        dialog.setFragmentManager(fragmentManager)
                .setLayoutRes(R.layout.dialog_login_user)
                .setCancelOutside(false)
                .setDimAmount(0.8f);
        return dialog;
    }

    @Override
    public void bindView(View v) {
        mInputName = (RectangleInputLayout) v.findViewById(R.id.inputUserName);
        mInputPassword = (RectangleInputLayout) v.findViewById(R.id.inputUserPassword);
        mDialogCancel = (TextView) v.findViewById(R.id.loginDialogCancel);
        mLoginLoadingLayout = (LinearLayout) v.findViewById(R.id.loginLoadingLayout);
        mLoginWarningTip = (TextView) v.findViewById(R.id.loginWarningTip);

   /*     String name = SPUtil.getStringValue(SPUtil.USER_NAME);
        if (!TextUtils.isEmpty(name)) {
            mInputName.setInputContent(name);
            mInputPassword.requestEditTextFocus();

            AppUtil.showSoftInput(mInputPassword.getInputEditText());
        } else {*/
            AppUtil.showSoftInput(mInputName.getInputEditText());
       // }
        mLoginBtn = (Button) v.findViewById(R.id.userLoginButton);
        mLoginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loginUserByPassword();
            }
        });
        mDialogCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!mIsLogining) {
                    AppUtil.hideSoftInput(getContext(), getDialog().getWindow());
                    LoginBottomDialog.this.dismiss();
                } else {
                    AppUtil.showShortToast(getContext().getApplicationContext(), "正在请求登录");
                }
            }
        });
        getDialog().setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (mIsLogining && keyCode == KeyEvent.KEYCODE_BACK) {
                    return true;
                }
                return false;
            }
        });
    }

    public void loginUserByPassword() {
        String name = mInputName.getInputContent();
        String password = mInputPassword.getInputContent();

        if (TextUtils.isEmpty(name)) {
            if (mLoginWarningTip.getVisibility() == View.GONE) {
                mLoginWarningTip.setVisibility(View.VISIBLE);
            }
            mLoginWarningTip.setText("用户名称不能为空");
            return;
        }
        if (TextUtils.isEmpty(password)) {
            if (mLoginWarningTip.getVisibility() == View.GONE) {
                mLoginWarningTip.setVisibility(View.VISIBLE);
            }
            mLoginWarningTip.setText("用户密码不能为空");
            return;
        }
        if (!NetWorkUtil.isNetConnected(getContext().getApplicationContext())) {
            if (mLoginWarningTip.getVisibility() == View.GONE) {
                mLoginWarningTip.setVisibility(View.VISIBLE);
            }
            mLoginWarningTip.setText("请先连接到网络");
            return;
        }
        showLoadingAnim();
        loginUserToServer(name, password);
    }

    public void showLoadingAnim() {
        if (mLoginWarningTip.getVisibility() == View.VISIBLE) {
            mLoginWarningTip.setVisibility(View.GONE);
        }

        mIsLogining = true;

        LinearLayout parent = (LinearLayout) mInputName.getParent();
        AppUtil.hideSoftInput(getContext(), getDialog().getWindow());

        mLoginBtn.setText("用户登录中");
        mLoginBtn.setClickable(false);

        parent.setVisibility(View.GONE);
        parent.setAnimation(AnimationUtils.loadAnimation(getContext().getApplicationContext(), R.anim.push_left_out));

        mLoginLoadingLayout.setVisibility(View.VISIBLE);
        mLoginLoadingLayout.setAnimation(AnimationUtils.loadAnimation(getContext().getApplicationContext(), R.anim.push_left_in));
    }

    public void loginUserToServer(final String name, String password) {

        RequestParams params = new RequestParams("visit", "Phone_Login");
        params.put("sAccountName", name);
        final String psd = MD5Util.EncoderByMd5(password);
        params.put("sAccountPwd", psd);
        params.put("IMEI", SystemUtil.getPhoneIMEI(getContext()));

        AsyncHttpUtil.postRequest(params, new TextHttpResponseHandler() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                loginFail("服务器无响应");
            }

            @Override
            public void onSuccess(int i, Header[] headers, String s) {
                JLog.d(TAG, "Login Response:" + s);
                if (!TextUtils.isEmpty(s)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        if (jsonObject.getBoolean(HttpConstant.RESPONSE_SUCCESS)) {
                            dismiss();
                            String code = jsonObject.getString(HttpConstant.REQUEST_CODE);
                            SPUtil.putStringValue(SPUtil.LOGIN_CODE, code);
                            SPUtil.putStringValue(SPUtil.USER_NAME, name);
                            SPUtil.putStringValue(SPUtil.PASS_WORD,psd);
                            SPUtil.putStringValue(SPUtil.PHONE_NAME, jsonObject.getString("pName"));
                            mCallback.loginUserSuccess(name);
                        } else {
                            loginFail(jsonObject.getString(HttpConstant.FAIL_REASON));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        loginFail("服务器无响应");
                    }
                } else {
                    loginFail("服务器无响应");
                }
            }
        });
    }

    public void loginFail(String reason) {
        mIsLogining = false;
        mLoginWarningTip.setVisibility(View.VISIBLE);
        mLoginWarningTip.setText(reason);

        LinearLayout parent = (LinearLayout) mInputName.getParent();
        mLoginLoadingLayout.setVisibility(View.GONE);
        mLoginLoadingLayout.setAnimation(AnimationUtils.loadAnimation(getContext().getApplicationContext(), R.anim.push_right_out));

        mInputPassword.requestEditTextFocus();
        parent.setVisibility(View.VISIBLE);
        parent.setAnimation(AnimationUtils.loadAnimation(getContext().getApplicationContext(), R.anim.push_right_in));

        mLoginBtn.setText("登录");
        mLoginBtn.setClickable(true);
    }

    @Override
    public void dismiss() {
        if (mInputName != null) {
            mInputName.getInputEditText().setCursorVisible(false);
            mInputName.getInputEditText().setText("");
        }
        if (mInputPassword != null) {
            mInputPassword.getInputEditText().setCursorVisible(false);
            mInputPassword.getInputEditText().setText("");
        }
        mIsLogining = false;
        super.dismiss();
    }

    public interface LoginCallback{
        void loginUserSuccess(String userName);
    }
}
